<?php

namespace app\models;

use common\models\Division;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "zs_contactor".
 *
 * @property integer $id
 * @property string $name
 * @property string $position
 * @property string $mobile
 * @property string $web_site
 * @property string $wechat
 * @property integer $create_time
 * @property integer $update_time
 * @property integer $is_hot
 * @property string $company_name
 */
class Contactor extends \yii\db\ActiveRecord
{

    public $cat;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'zs_contactor';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cat' , 'city_id' , 'company_name' , 'name' , 'mobile'] , 'required'],
            [['create_time', 'update_time', 'is_hot'], 'integer'],
            [['name'], 'string', 'max' => 10],
            [['position', 'mobile'], 'string', 'max' => 20],
            [['web_site'], 'string', 'max' => 200],
            [['wechat', 'company_name'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '联系人名称',
            'position' => '职位',
            'mobile' => '手机号',
            'web_site' => '网址',
            'wechat' => '微信号',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'is_hot' => '是否推荐 0否；1是',
            'company_name' => '公司名称',
            'cat' => '主营产品',
        ];
    }

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time'
                ],
            ]
        ];
    }

    public function saveCat()
    {
        if(!is_array($this->cat) || empty($this->cat)){
            $this->addError('cat' ,'未选择主营产品');
            return false;
        }
        $catModel = new ContactorCat();
        foreach($this->cat as $v) {
            $catModel->isNewRecord = true;
            $catModel->id = null;
            $catModel->cat_id = $v;
            $catModel->contactor_id = $this->id;
            if(!$catModel->save()){
                Yii::error('保存分类失败,contactor_id:'.$this->id.' 分类id：'.$v);
                continue;
            }
        }
    }

    public function getCityName()
    {

        $cityModel = Division::getCityById($this->city_id);
        $a_province = Division::getProvinceByPid($cityModel->parent_id);

        return $a_province['division_name'].$cityModel->division_name;

    }

}
